package org.nfyszny.zzzs.modules.utils;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;


/**
 * @author 笑小枫
 * @date 2022/8/15
 * @see <a href="https://www.xiaoxiaofeng.com">https://www.xiaoxiaofeng.com</a>
 */
public class PdfUtil {
    public static void main(String[] args) throws IOException {
        PdfReader reader=new PdfReader
                ("F:/mb.pdf");
        System.out.println("reader = " + reader);
    }
    private PdfUtil() {

    }

    /**
     * 利用模板生成pdf
     *
     * @param data         写入的数据
     * @param out          自定义保存pdf的文件流
     * @param templatePath pdf模板路径
     */
    public static void fillTemplate(Map<String, Object> data, FileOutputStream out, String templatePath) {
        PdfReader reader;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        try {
            // 读取pdf模板
            reader = new PdfReader("E:\\mb.pdf");
//            reader = new PdfReader("D:\\xm\\种植追溯管理系统\\ur-f-nfyszny-zzzs-parent\\ur-f-nfyszny-zzzs-system\\ur-f-nfyszny-zzzs-03\\src\\main\\resources\\mb.pdf");
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields acroFields = stamper.getAcroFields();
            // 赋值
            for (String name : acroFields.getFields().keySet()) {
                String value = data.get(name) != null ? data.get(name).toString() : null;

                // 处理日期格式
                if (name.contains("Time")) {
                    System.out.println("时间");
                    value = value.replace("-", "/"); // 将日期格式中的连字符改为斜杠
                } else if (name.contains("type")) {
                    value = "\u4EA7\u54C1";
                    System.out.println(value);
                }
                acroFields.setFieldProperty(name, "textfont", BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), null);
                acroFields.setField(name, value);
            }
            // 如果为false那么生成的PDF文件还能编辑，一定要设为true
            stamper.setFormFlattening(true); // 强制刷新 PDF 表单
            stamper.close();
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage);
            doc.close();
            bos.close();
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        }
    }



}


